//
//  OrderFileViewController.swift
//  FeastBooking
//
//  Created by Imon on 2017/11/1.
//  Copyright © 2017年 Imon. All rights reserved.
//

import UIKit
import RxSwift

enum OrderFileType {
    case contract
    case payment    
}

class OrderFileViewController: UIViewController {
    
    fileprivate let activityView: UIActivityIndicatorView = {
        let view = UIActivityIndicatorView(activityIndicatorStyle: .gray)
        view.startAnimating()
        return view
    }()

    var timer: Timer = Timer()
    
    var actionSheet: UIAlertController!
    
    var visualView: UIVisualEffectView?
    
    let statusMessage: UILabel = {
        let label = UILabel()
        label.textColor = proceededColor
        label.textAlignment = .left
        label.font = AppFont(size: 20)
        label.text = LanguageHelper.getString(key: "UPLOADING")
        return label
    }()
    
    var fileType: OrderFileType?
    
    var order: UserOrderDetail?
    
    var orderVM: OrderViewModel?
    
    var completion: (() -> Void)?
    
    let disposeBag = DisposeBag()
    
    var scrollView: UIScrollView?
    
    var imageViews: [OrderImageView] = []
    
    var deleted = ""
    
    let addImageView = OrderAddImageView()
    
    var top: CGFloat = 0
    
    var files: [String]?
    
    let editField: UITextField = {
        let textfield = UITextField()
        textfield.font = AppFont(size: 14)
        textfield.placeholder = LanguageHelper.getString(key: "WRITE_PAID_AMOUNT")
        textfield.tintColor = UIColor.black
        textfield.textColor = UIColor.gray
        textfield.keyboardType = .decimalPad
        return textfield
    }()
    
    var needToPost: Bool = false
    
    var isEditable: Bool = true
    
    var canEdit: Bool = false
    
    var showing: Bool = false
    
    let detailScrollView: UIScrollView = UIScrollView()
    
    let detailImageView: UIImageView = {
        let imageView = UIImageView()
        imageView.contentMode = .scaleAspectFill
        imageView.layer.masksToBounds = true
        return imageView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = lightSaperatorColor
        initVM()
        
        scrollView = UIScrollView()
        scrollView?.backgroundColor = UIColor.white
        scrollView?.frame = CGRect(x: 0, y: 0, width: self.view.bounds.width, height: self.view.bounds.height)
        scrollView?.showsVerticalScrollIndicator = false
        scrollView?.showsHorizontalScrollIndicator = false
        scrollView?.isScrollEnabled = true
        scrollView?.alwaysBounceVertical = true
        scrollView?.autoresizingMask = UIViewAutoresizing.flexibleHeight
        
        setBackBarItem()
        
        if let status = order?.orderStatus {
            let step = orderSteps[status]!
            if ((fileType == .contract && step < 2) || (fileType == .payment && step < 4)) && canEdit {
                let rightBt = UIButton()
                rightBt.contentHorizontalAlignment = .right
                rightBt.setTitle(LanguageHelper.getString(key: "SUBMIT"), for: .normal)
                rightBt.setTitleColor(doneItemButtonColor, for: .normal)
                rightBt.addTarget(self, action: #selector(submit(_:)), for: .touchUpInside)
                rightBt.sizeToFit()
                self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(customView: rightBt)
            }
        }
        
        if let type = fileType {
            switch type {
            case .contract:
                setContract()
            case .payment:
                setPayment()
            }
        }
        
        let tapGesture = UITapGestureRecognizer()
        tapGesture.addTarget(self, action: #selector(tapAddImage(_:)))
        addImageView.addGestureRecognizer(tapGesture)
        
        self.scrollView?.delegate = self
        self.view.addSubview(scrollView!)
        
        detailScrollView.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.width)
        detailScrollView.delegate = self
        detailScrollView.maximumZoomScale = 2.0
        detailScrollView.minimumZoomScale = 1.0
        detailScrollView.showsVerticalScrollIndicator = false
        detailScrollView.showsHorizontalScrollIndicator = false
        detailImageView.frame = CGRect(x: 0, y: 0, width: 0, height: 0)
        detailScrollView.frame = CGRect(x: 0, y: 0, width: 0, height: 0)
        detailScrollView.addSubview(detailImageView)
        self.view.insertSubview(detailScrollView, aboveSubview: scrollView!)
        let tapDIGesture = UITapGestureRecognizer()
        tapDIGesture.addTarget(self, action: #selector(tapDetailImageView(_:)))
        self.view.addGestureRecognizer(tapDIGesture)
        
        setActionSheet()
        
        setVisualView()
    }
    
    func setVisualView() {
        let effect = UIBlurEffect(style: .light)
        visualView = UIVisualEffectView(effect: effect)
        visualView?.frame = UIScreen.main.bounds
        
        activityView.center = CGPoint(x: visualView!.frame.width/2.0, y: visualView!.frame.height/2.0)
        visualView?.contentView.addSubview(activityView)
        visualView?.contentView.addSubview(self.statusMessage)        
    }
    
    func setMessage(message: String) {
        statusMessage.text = message
        let maxSize = CGSize(width: self.view.bounds.width, height: 40)
        let messageSize = TextSize.textSize(text: statusMessage.text!, font: statusMessage.font, maxSize: maxSize)
        statusMessage.frame = CGRect(x: (self.view.bounds.width - messageSize.width) / 2, y: self.view.bounds.height / 2 - messageSize.height - 30, width: messageSize.width, height: messageSize.height)
    }
    
    func setActionSheet() {
        actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
        actionSheet.addAction(UIAlertAction(title: LanguageHelper.getString(key: "CANCEL"), style: .cancel, handler: { _ in
            
        }))
        actionSheet.addAction(UIAlertAction(title: LanguageHelper.getString(key: "CHOOSE_FROM_LIBRARY"), style: .default, handler: { [unowned self] _ in
            let imagePickerController = UIImagePickerController()
            imagePickerController.sourceType = .photoLibrary
            imagePickerController.delegate = self
            self.present(imagePickerController, animated: true, completion: nil)
        }))
        actionSheet.addAction(UIAlertAction(title: LanguageHelper.getString(key: "TAKE_PHOTO"), style: .default, handler: { [unowned self] _ in
            if UIImagePickerController.isSourceTypeAvailable(.camera) {
                let imagePickerController = UIImagePickerController()
                imagePickerController.sourceType = .camera
                imagePickerController.delegate = self
                self.present(imagePickerController, animated: true, completion: nil)
            } else {
                self.showPromptView(message: LanguageHelper.getString(key: "CAMERO_DOWN"), confirmText: LanguageHelper.getString(key: "OK"))
            }
        }))
    }

    func tapDetailImageView(_ sender: UITapGestureRecognizer) {
        if showing {
            UIView.animate(withDuration: 0.3, animations: { [unowned self] in
                self.detailImageView.frame = CGRect(x: 0, y: 0, width: 0, height: 0)
                self.detailScrollView.frame = CGRect(x: 0, y: 0, width: 0, height: 0)
                self.detailScrollView.contentSize = CGSize(width: 0, height: 0)
            }, completion: nil)
            self.navigationController?.setNavigationBarHidden(false, animated: true)
        }
    }
    
    func setContract() {
        setImageView()
        if isEditable {
            self.navigationItem.title = LanguageHelper.getString(key: "CONTRACT_MNT")
        } else {
            self.navigationItem.title = LanguageHelper.getString(key: "CONTRACT_MNT_PASS")
        }
    }
    
    func setPayment() {
        let payView = UIView()
        payView.backgroundColor = UIColor.white
        payView.frame = CGRect(x: 0, y: 0, width: self.view.bounds.width, height: menuHeight)
        let titleLabel = UILabel()
        titleLabel.font = AppFont(size: 14)
        titleLabel.textColor = UIColor.black
        titleLabel.text = LanguageHelper.getString(key: "PAID_AMOUNT")
        let maxSize = CGSize(width: self.view.bounds.width, height: 30)
        let titleWidth = TextSize.textSize(text: titleLabel.text!, font: moreFont(size: 14), maxSize: maxSize).width
        titleLabel.frame = UIEdgeInsetsInsetRect(payView.bounds, UIEdgeInsetsMake(10, 10, 10, payView.bounds.width - titleWidth - 10))
        editField.frame = UIEdgeInsetsInsetRect(payView.bounds, UIEdgeInsetsMake(10, payView.bounds.width - 100 - 10, 10, 10))
        let paySaperator = UIView()
        paySaperator.backgroundColor = lightSaperatorColor
        paySaperator.frame = UIEdgeInsetsInsetRect(payView.bounds, UIEdgeInsetsMake(payView.bounds.height - 0.5, 0, 0, 0))
        payView.addSubview(editField)
        payView.addSubview(titleLabel)
        payView.addSubview(paySaperator)
        self.scrollView!.addSubview(payView)
        setImageView()
        if let payment = order?.orderPaymentDTO {
            if let amount = payment.amountPaid {
                self.editField.text = "\(amount)"
            }
        }
        if isEditable {
            self.navigationItem.title = LanguageHelper.getString(key: "PAYMENT_MNT")
        } else {
            self.navigationItem.title = LanguageHelper.getString(key: "PAYMENT_MNT_PASS")
            self.editField.isEnabled = false
        }
        if !canEdit {
            self.editField.isEnabled = false
            if self.editField.text == "" {
               self.editField.text = LanguageHelper.getString(key: "NO_RESULT")
            }
        }
        
    }
    
    func setImageView() {
        if fileType == .contract {
            if let contractDTO = order?.orderContractDTO {
                files = contractDTO.files
                if let approvalStatus = contractDTO.approvalStatus {
                    if approvalStatus == "APPROVED" {
                        isEditable = false
                    }
                }
                if files != nil {
                    if (files?.count)! > 0 {
                        for file in files! {
                            let orderImageView = OrderImageView()
                            orderImageView.delegate = self
                            orderImageView.initValue(url: file, isEditable: isEditable && canEdit)
                            imageViews.append(orderImageView)
                        }
                    }
                }
            } else {
                //尚未有合同信息，需要创建
                needToPost = true
            }
        } else {
            top = menuHeight
            if let paymentDTO = order?.orderPaymentDTO {
                files = paymentDTO.files
                if let approvalStatus = paymentDTO.approvalStatus {
                    if approvalStatus == "APPROVED" {
                        isEditable = false
                    }
                }
                if let paid = paymentDTO.amountPaid {
                    self.editField.text = "$\(paid)"
                }
                if files != nil {
                    if (files?.count)! > 0 {
                        for file in files! {
                            let orderImageView = OrderImageView()
                            orderImageView.delegate = self
                            orderImageView.initValue(url: file, isEditable: isEditable && canEdit)
                            imageViews.append(orderImageView)
                        }
                    }
                }
            } else {
                needToPost = true
            }
        }
        
        layoutImageView()
    }
    
    func layoutImageView() {
        let gap: CGFloat = 15
        let imageViewWidth = (self.view.bounds.width - 4 * gap) / 3
        let imageViewHeight = imageViewWidth * 11/10
        
        if imageViews.count > 0 {
            for i in 0...imageViews.count - 1 {
                let x = i % 3
                let y = i / 3
                imageViews[i].frame = CGRect(x: gap + (imageViewWidth + gap) * CGFloat(x), y: top + gap + (imageViewHeight + gap) * CGFloat(y), width: imageViewWidth, height: imageViewHeight)
                self.scrollView?.addSubview(imageViews[i])
            }
        }
        
        if isEditable && canEdit {
            let adX = imageViews.count % 3
            let adY = imageViews.count / 3
            addImageView.frame = CGRect(x: gap + (imageViewWidth + gap) * CGFloat(adX), y: top + gap + (imageViewHeight + gap) * CGFloat(adY) + imageViewWidth / 10, width: imageViewWidth, height: imageViewWidth)
            self.scrollView?.addSubview(addImageView)
            self.scrollView?.contentSize = CGSize(width: self.view.bounds.width, height: addImageView.frame.origin.y + addImageView.frame.height)
        }
    }
    
    func initVM() {
        let authManager = AuthManager.share
        if authManager.hasLogined() {
            if let token = authManager.getToken() as? String {
                orderVM = OrderViewModel(token: token)
            }
        }
    }
    
    func submit(_ sender: UIBarButtonItem) {
        var files: [UIImage] = []
        print("deleted: \(deleted)")
        for imageView in imageViews {
            if imageView.filename == "new" {
                files.append(imageView.imageView.image!)
            }
        }
        if fileType == .contract {
            showWaitView()
            orderVM?.postContract(id: (self.order?.id)!, deleted: deleted, images: files).subscribe(onNext: {[unowned self] response in
                //print(response)
                if response == "true" { //操作成功
                    self.operationSuccess()
                } else {
                    self.operationFail()
                }
            })
            .addDisposableTo(disposeBag)
        } else if fileType == .payment {
            if let amount = editField.text {
                if amount != "" {
                    guard let amountN = Double(amount) else {
                        self.showPromptView(message: LanguageHelper.getString(key: "CORRECT_AMOUNT_FORMMAT"), confirmText: LanguageHelper.getString(key: "OK"))
                        return
                    }
                    showWaitView()
                    orderVM?.postPayment(id: (self.order?.id)!, deleted: deleted, images: files, amountPaid: amountN).subscribe(onNext: {[unowned self] response in
                        //print(response)
                        if response == "true" { //操作成功
                            self.operationSuccess()
                        } else {
                            self.operationFail()
                        }
                    }, onError: { error in
                        print("error!!\(error)")
                    })
                    .addDisposableTo(disposeBag)
                } else {
                    self.showPromptView(message: LanguageHelper.getString(key: "AMOUNT_NEEDED"), confirmText: LanguageHelper.getString(key: "OK"))
                }
            } else {
                self.showPromptView(message: LanguageHelper.getString(key: "AMOUNT_NEEDED"), confirmText: LanguageHelper.getString(key: "OK"))
            }
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func tapAddImage(_ sender: UITapGestureRecognizer) {
        self.present(actionSheet, animated: true, completion: nil)
    }
    
    func addFile(image: UIImage) {
        let imageView = OrderImageView()
        imageView.initValue(image: image, isEditable: isEditable)
        imageView.delegate = self
        imageViews.append(imageView)
        layoutImageView()
    }
    
    func calculateImageRect(image: UIImage) -> CGRect {
        var width: CGFloat = 0.0
        var height: CGFloat = 0.0
        var photoScale: CGFloat = 0.0
        if image.size.height > image.size.width {
            width = self.view.frame.width
            photoScale = image.size.width / width
            height = image.size.height / photoScale
        } else {
            height = self.view.frame.height
            photoScale = image.size.height / height
            width = image.size.width / photoScale
        }
        return CGRect(x: 0, y: 0, width: width, height: height)
    }
    
    func showWaitView() {
        setMessage(message: LanguageHelper.getString(key: "UPLOADING"))
        self.navigationController?.setNavigationBarHidden(true, animated: true)
        self.view.addSubview(visualView!)
        self.activityView.startAnimating()
        timer = Foundation.Timer.scheduledTimer(timeInterval: 30, target: self, selector: #selector(timeout), userInfo: nil, repeats: false)
    }
    
    func operationSuccess() {
        timer.invalidate()
        setMessage(message: LanguageHelper.getString(key: "OPERATION_SUCCESS"))
        self.activityView.stopAnimating()
        DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
            self.visualView?.removeFromSuperview()
            self.navigationController?.setNavigationBarHidden(false, animated: true)
            if let function = self.completion {
                function()
            }
            self.navigationController?.popViewController(animated: true)
        }
    }
    
    func operationFail() {
        timer.invalidate()
        setMessage(message: LanguageHelper.getString(key: "OPERATION_FAIL"))
        DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
            self.activityView.stopAnimating()
            self.visualView?.removeFromSuperview()
            self.navigationController?.setNavigationBarHidden(false, animated: true)
            if let function = self.completion {
                function()
            }
            self.navigationController?.popViewController(animated: true)
        }
    }
    
    func timeout() {
        timer.invalidate()
        setMessage(message: LanguageHelper.getString(key: "TIMEOUT"))
        DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
            self.activityView.stopAnimating()
            self.visualView?.removeFromSuperview()
            self.navigationController?.setNavigationBarHidden(false, animated: true)
            if let function = self.completion {
                function()
            }
            self.navigationController?.popViewController(animated: true)
        }
    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

extension OrderFileViewController: UIScrollViewDelegate {
    
    func viewForZooming(in scrollView: UIScrollView) -> UIView? {
        return self.detailImageView
    }
    
    func scrollViewDidZoom(_ scrollView: UIScrollView) {
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        self.editField.resignFirstResponder()
    }
}

extension OrderFileViewController: OrderImageViewDelegate {
    
    func deleteImage(orderImageView: OrderImageView, deleted: String) {
        if deleted != "new" {
            self.deleted += "\(deleted);"
        }
        UIView.animate(withDuration: 0.3, animations: { [unowned self] in
            orderImageView.removeFromSuperview()
            if let index = self.imageViews.index(of: orderImageView) {
                self.imageViews.remove(at: index)
                self.layoutImageView()
            }
        }, completion: nil)
    }
    
    func showDetailImage(image: UIImage) {
        self.navigationController?.setNavigationBarHidden(true, animated: true)
        UIView.animate(withDuration: 0.3, animations: { [unowned self] in
            self.detailImageView.image = image
            self.detailImageView.frame = self.calculateImageRect(image: image)
            self.detailScrollView.frame = self.view.bounds
            self.detailScrollView.contentSize = CGSize(width: self.detailImageView.bounds.width, height: self.detailImageView.bounds.height)
        }, completion: nil)
        showing = true
    }
}

extension OrderFileViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        dismiss(animated: true, completion: nil)
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        guard let selectedImage = info[UIImagePickerControllerOriginalImage] as?
            UIImage else {
                fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")
        }
        self.addFile(image: selectedImage)
        dismiss(animated: true, completion: nil)
    }
}
